#include "BluetoothSerial.h"
#include <ESP32Servo.h>
#include <DHT.h>

//#define USE_PIN // Uncomment this to use PIN during pairing. The pin is specified on the line below
const char *pin = "1234"; // Change this to more secure PIN.

String device_name = "ESP32-BT-Slave";

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run make menuconfig to and enable it
#endif

#if !defined(CONFIG_BT_SPP_ENABLED)
#error Serial Bluetooth not available or not enabled. It is only available for the ESP32 chip.
#endif

BluetoothSerial SerialBT;

// Define los pines de los LEDs
int led1 = 2; // Cambia al número de pin correcto para tu LED 1
int led2 = 4; // Cambia al número de pin correcto para tu LED 2
int led3 = 22; // Cambia al número de pin correcto para tu LED 3
int led4 = 12;
// Define el pin del servo motor
int servoPin = 19; // Cambia al número de pin correcto para tu servo motor

#define DHTPIN 5
#define DHTTYPE DHT11

// Crea una instancia del objeto Servo
Servo myServo;

float temp;

DHT dht(DHTPIN, DHTTYPE);
void setup() {
  Serial.begin(115200);
  SerialBT.begin(device_name); //Bluetooth device name
  Serial.printf("The device with name \"%s\" is started.\nNow you can pair it with Bluetooth!\n", device_name.c_str());
  //Serial.printf("The device with name \"%s\" and MAC address %s is started.\nNow you can pair it with Bluetooth!\n", device_name.c_str(), SerialBT.getMacString()); // Use this after the MAC method is implemented
  
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  // Inicializa el servo y colócalo en la posición inicial
  myServo.attach(servoPin);
  myServo.write(0); // Posición inicial (0 grados)
  dht.begin();

  #ifdef USE_PIN
    SerialBT.setPin(pin);
    Serial.println("Using PIN");
  #endif
}

void loop() {

  if (SerialBT.available()) {
    String command = SerialBT.readString();

    if (command == "E1") {
      digitalWrite(led1, HIGH);
    } else if (command == "A1") {
      digitalWrite(led1, LOW);
    } else if (command == "E2") {
      digitalWrite(led2, HIGH);
    } else if (command == "A2") {
      digitalWrite(led2, LOW);
    } else if (command == "E3") {
      digitalWrite(led3, HIGH);
      digitalWrite(led4, HIGH);
    } else if (command == "A3") {
      digitalWrite(led3, LOW);
      digitalWrite(led4, LOW);
    } else if (command == "C") {
      myServo.write(90); // Gira el servo a 90 grados
    } else if (command == "O") {
      myServo.write(0); // Vuelve el servo a la posición inicial (0 grados)
    }
  }
  delay(20);
}